#include <stdio.h>
#include <string.h>
#include <time.h>
#include "member.h"

#define MEMBER_INFO_FILE "member_info.dat"
#define ADMIN_INFO_FILE "admin_info.dat"
#define ACCESS_RECORD_FILE "access_record.dat"
#define MEMBER_ID_BASE 100001

static int admin_logged_in = 0;

/* 检查文件是否存在 */
int file_exists(const char *filename)
{
    FILE *file = fopen(filename, "rb");
    if (file)
    {
        fclose(file);
        return 1;
    }
    return 0;
}

/* 检查并创建数据目录 - 简化版本 */
void check_data_dir(void)
{
    // 不需要创建目录，直接检查文件是否存在
    // 这个函数保留是为了兼容性，但不再需要实际创建目录
}

/* 获取新的会员ID */
static unsigned int get_new_mid(void)
{
    member_info mi;
    unsigned int mid = MEMBER_ID_BASE;
    FILE* fp = fopen(MEMBER_INFO_FILE, "rb");

    if(fp == NULL)
    {
        return mid;
    }

    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    
    if(file_size >= (long)sizeof(mi))
    {
        fseek(fp, -(long)sizeof(mi), SEEK_END);
        if(fread(&mi, sizeof(mi), 1, fp) == 1)
        {
            mid = mi.mid + 1;
        }
    }

    fclose(fp);
    return mid;
}

/* 会员注册 */
void member_reg(void)
{
    member_info mi;
    memset(&mi, 0, sizeof(mi));
    mi.mid = get_new_mid();
    mi.delete_state = 0;

    printf("请按照如下提示填写会员的信息\n");
    printf("卡号：");
    scanf("%10s", mi.card);
    printf("会员姓名：");
    scanf("%19s", mi.name);
    printf("会员手机号：");
    scanf("%11s", mi.number);
    printf("会员性别（1-女 2-男 3-未知）：");
    scanf("%d", (int*)&mi.s);
    printf("会员类型（1-年卡 2-月卡 3-次卡）：");
    scanf("%d", (int*)&mi.mt);
    
    if(mi.mt == next_card)
    {
        printf("剩余次数：");
        scanf("%d", &mi.remain_cnt);
    }
    else
    {
        mi.remain_cnt = 0;
    }
    
    mi.reg_time = time(NULL);

    if(mi.mt == monthly_card)
        mi.expire_time = mi.reg_time + 30 * 24 * 60 * 60;
    else if(mi.mt == annual_card)
        mi.expire_time = mi.reg_time + 365 * 24 * 60 * 60;
    else
        mi.expire_time = mi.reg_time + 365 * 24 * 60 * 60; // 次卡也设置一年有效期

    FILE* fp = fopen(MEMBER_INFO_FILE, "ab");
    if(fp == NULL)
    {
        printf("会员注册失败：无法打开文件\n");
        return;
    }
    
    fwrite(&mi, sizeof(mi), 1, fp);
    fclose(fp);
    
    printf("会员注册成功！会员ID：%u，恭喜您成为iceredtea basketball member!\n", mi.mid);
}

/* 显示会员信息 */
void member_show(void)
{
    member_info mi;
    char search_term[20];
    int found = 0;

    printf("请输入卡号、会员ID、姓名或手机号：");
    scanf("%19s", search_term);

    FILE* fp = fopen(MEMBER_INFO_FILE, "rb");
    if(fp == NULL)
    {
        printf("暂无会员数据！\n");
        return;
    }   
    
    printf("\n查询结果：\n");
    printf("=============================================\n");
    
    while(fread(&mi, sizeof(mi), 1, fp) == 1)
    {
        if(mi.delete_state == 1) continue;
        
        char mid_str[20];
        sprintf(mid_str, "%u", mi.mid);
        
        if(strcmp(search_term, mi.card) == 0 || 
           strcmp(search_term, mid_str) == 0 ||
           strcmp(search_term, mi.name) == 0 ||
           strcmp(search_term, mi.number) == 0)
        {
            found = 1;
            printf("卡号：%s\n", mi.card);
            printf("会员ID：%u\n", mi.mid);
            printf("姓名：%s\n", mi.name);
            printf("手机号：%s\n", mi.number);
            printf("性别：%s\n", mi.s == female ? "女" : (mi.s == male ? "男" : "未知"));
            printf("会员类型：%s\n", mi.mt == annual_card ? "年卡" : 
                                  (mi.mt == monthly_card ? "月卡" : "次卡"));
            
            if(mi.mt == next_card)
                printf("剩余次数：%d\n", mi.remain_cnt);
            
            char reg_time[20], expire_time[20];
            strftime(reg_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&mi.reg_time));
            strftime(expire_time, 20, "%Y-%m-%d %H:%M:%S", localtime(&mi.expire_time));
            
            printf("注册时间：%s\n", reg_time);
            printf("到期时间：%s\n", expire_time);
            printf("=============================================\n");
        }
    }

    if(!found)
    {
        printf("未找到匹配的会员信息！\n");
    }
    
    fclose(fp);
}

/* 管理员登录 */
int admin_login(void)
{
    admin_info admin;
    char username[20], password[20];
    
    printf("管理员登录\n");
    printf("用户名：");
    scanf("%19s", username);
    printf("密码：");
    scanf("%19s", password);
    
    FILE* fp = fopen(ADMIN_INFO_FILE, "rb");
    if(fp == NULL)
    {
        // 默认管理员账户
        if(strcmp(username, "admin") == 0 && strcmp(password, "admin123") == 0)
        {
            admin_logged_in = 1;
            printf("登录成功！\n");
            return 1;
        }
    }
    else
    {
        while(fread(&admin, sizeof(admin), 1, fp) == 1)
        {
            if(strcmp(username, admin.username) == 0 && 
               strcmp(password, admin.password) == 0)
            {
                admin_logged_in = 1;
                fclose(fp);
                printf("登录成功！\n");
                return 1;
            }
        }
        fclose(fp);
    }
    
    printf("用户名或密码错误！\n");
    return 0;
}

/* 检查管理员是否登录 */
int is_admin_logged_in(void)
{
    if(!admin_logged_in)
    {
        printf("请先以管理员身份登录！\n");
        return 0;
    }
    return 1;
}

/* 会员注销 */
void member_delete(void)
{
    if(!is_admin_logged_in()) return;
    
    member_info mi;
    unsigned int mid;
    int found = 0;
    
    printf("请输入要注销的会员ID：");
    scanf("%u", &mid);
    
    FILE* fp = fopen(MEMBER_INFO_FILE, "r+b");
    if(fp == NULL)
    {
        printf("暂无会员数据！\n");
        return;
    }
    
    while(fread(&mi, sizeof(mi), 1, fp) == 1)
    {
        if(mi.mid == mid && mi.delete_state == 0)
        {
            found = 1;
            printf("找到会员：%s（ID：%u），确认注销？(y/n)：", mi.name, mi.mid);
            char confirm;
            scanf(" %c", &confirm);
            
            if(confirm == 'y' || confirm == 'Y')
            {
                mi.delete_state = 1;
                fseek(fp, -(long)sizeof(mi), SEEK_CUR);
                fwrite(&mi, sizeof(mi), 1, fp);
                printf("会员注销成功！\n");
            }
            else
            {
                printf("已取消注销操作。\n");
            }
            break;
        }
    }
    
    if(!found)
    {
        printf("未找到会员ID：%u\n", mid);
    }
    
    fclose(fp);
}

/* 修改会员信息 */
void member_modify(void)
{
    if(!is_admin_logged_in()) return;
    
    member_info mi;
    unsigned int mid;
    int found = 0;
    
    printf("请输入要修改的会员ID：");
    scanf("%u", &mid);
    
    FILE* fp = fopen(MEMBER_INFO_FILE, "r+b");
    if(fp == NULL)
    {
        printf("暂无会员数据！\n");
        return;
    }
    
    while(fread(&mi, sizeof(mi), 1, fp) == 1)
    {
        if(mi.mid == mid && mi.delete_state == 0)
        {
            found = 1;
            printf("当前会员信息：\n");
            printf("1. 姓名：%s\n", mi.name);
            printf("2. 手机号：%s\n", mi.number);
            printf("3. 性别：%s\n", mi.s == female ? "女" : (mi.s == male ? "男" : "未知"));
            printf("4. 会员类型：%s\n", mi.mt == annual_card ? "年卡" : 
                                      (mi.mt == monthly_card ? "月卡" : "次卡"));
            if(mi.mt == next_card)
                printf("5. 剩余次数：%d\n", mi.remain_cnt);
            
            printf("请选择要修改的项（0-保存并退出）：");
            int choice;
            scanf("%d", &choice);
            
            while(choice != 0)
            {
                switch(choice)
                {
                    case 1:
                        printf("新姓名：");
                        scanf("%19s", mi.name);
                        break;
                    case 2:
                        printf("新手机号：");
                        scanf("%11s", mi.number);
                        break;
                    case 3:
                        printf("新性别（1-女 2-男 3-未知）：");
                        scanf("%d", (int*)&mi.s);
                        break;
                    case 4:
                        printf("新会员类型（1-年卡 2-月卡 3-次卡）：");
                        scanf("%d", (int*)&mi.mt);
                        if(mi.mt != next_card)
                            mi.remain_cnt = 0;
                        break;
                    case 5:
                        if(mi.mt == next_card)
                        {
                            printf("新剩余次数：");
                            scanf("%d", &mi.remain_cnt);
                        }
                        else
                        {
                            printf("只有次卡可以修改剩余次数！\n");
                        }
                        break;
                    default:
                        printf("无效选择！\n");
                        break;
                }
                printf("请选择要修改的项（0-保存并退出）：");
                scanf("%d", &choice);
            }
            
            fseek(fp, -(long)sizeof(mi), SEEK_CUR);
            fwrite(&mi, sizeof(mi), 1, fp);
            printf("会员信息修改成功！\n");
            break;
        }
    }
    
    if(!found)
    {
        printf("未找到会员ID：%u\n", mid);
    }
    
    fclose(fp);
}

/* 会员入场离场记录 */
void member_access(void)
{
    member_info mi;
    char card_num[11];
    int found = 0;
    
    printf("请刷卡（输入卡号）：");
    scanf("%10s", card_num);
    
    // 检查会员是否存在且有效
    FILE* fp = fopen(MEMBER_INFO_FILE, "rb");
    if(fp == NULL)
    {
        printf("暂无会员数据！\n");
        return;
    }
    
    while(fread(&mi, sizeof(mi), 1, fp) == 1)
    {
        if(strcmp(card_num, mi.card) == 0 && mi.delete_state == 0)
        {
            found = 1;
            break;
        }
    }
    fclose(fp);
    
    if(!found)
    {
        printf("卡号无效或会员已注销！\n");
        return;
    }
    
    // 检查会员是否过期
    if(time(NULL) > mi.expire_time)
    {
        printf("会员已过期，无法入场！\n");
        return;
    }
    
    // 检查次卡剩余次数
    if(mi.mt == next_card && mi.remain_cnt <= 0)
    {
        printf("次卡次数已用完，无法入场！\n");
        return;
    }
    
    // 处理入场离场
    FILE* access_fp = fopen(ACCESS_RECORD_FILE, "a+b");
    if(access_fp == NULL)
    {
        printf("无法打开记录文件！\n");
        return;
    }
    
    access_record ar;
    int in_venue = 0;
    long last_pos = -1;
    
    // 查找最近的记录
    fseek(access_fp, 0, SEEK_END);
    long file_size = ftell(access_fp);
    
    if(file_size >= (long)sizeof(ar))
    {
        fseek(access_fp, -(long)sizeof(ar), SEEK_END);
        while(ftell(access_fp) >= 0)
        {
            last_pos = ftell(access_fp);
            if(fread(&ar, sizeof(ar), 1, access_fp) == 1)
            {
                if(ar.mid == mi.mid && ar.status == 1)
                {
                    in_venue = 1;
                    break;
                }
            }
            
            if(ftell(access_fp) < (long)sizeof(ar) * 2)
                break;
                
            fseek(access_fp, -(long)sizeof(ar) * 2, SEEK_CUR);
        }
    }
    
    if(in_venue)
    {
        // 离场处理
        ar.exit_time = time(NULL);
        ar.status = 0;
        fseek(access_fp, last_pos, SEEK_SET);
        fwrite(&ar, sizeof(ar), 1, access_fp);
        
        // 如果是次卡，减少次数
        if(mi.mt == next_card)
        {
            FILE* member_fp = fopen(MEMBER_INFO_FILE, "r+b");
            if(member_fp != NULL)
            {
                member_info temp_mi;
                while(fread(&temp_mi, sizeof(temp_mi), 1, member_fp) == 1)
                {
                    if(temp_mi.mid == mi.mid)
                    {
                        temp_mi.remain_cnt--;
                        fseek(member_fp, -(long)sizeof(temp_mi), SEEK_CUR);
                        fwrite(&temp_mi, sizeof(temp_mi), 1, member_fp);
                        break;
                    }
                }
                fclose(member_fp);
            }
        }
        
        printf("会员%s离场成功！\n", mi.name);
    }
    else
    {
        // 入场处理
        ar.mid = mi.mid;
        ar.enter_time = time(NULL);
        ar.exit_time = 0;
        ar.status = 1;
        fseek(access_fp, 0, SEEK_END);
        fwrite(&ar, sizeof(ar), 1, access_fp);
        printf("会员%s入场成功！\n", mi.name);
    }
    
    fclose(access_fp);
}